package com.acxy.cms.controller;

import com.acxy.ants.common.kit.DeviceKit;
import com.acxy.ants.core.annotation.Autowired;
import com.acxy.ants.resful.annotation.Controller;
import com.acxy.ants.resful.annotation.GET;
import com.acxy.ants.resful.annotation.POST;
import com.acxy.ants.resful.annotation.Param;
import com.acxy.ants.resful.bean.Page;
import com.acxy.ants.resful.render.Json;
import com.acxy.cms.entity.Article;
import com.acxy.cms.service.ArticleService;
import com.acxy.cms.servlet.WebSocketTips;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;

/**
 * 用户模块
 * @author MrShun
 * @version 1.0
 * @Date 2017-06-23
 */
@Controller("article")
public class ArticleAjax {

    @Autowired
    private ArticleService articleService;

    /**
     * 获取文章分页列表
     * @param pageIndex 整型 1 当前页 必须是整型!
     * @param pageSize 整型 1 每页大小 必须是整型!
     * @param catIds 数组 1 所属分类 必须是整型!
     * @return
     */
    @POST("/page")
    public Object page(@Param(value = "^(-|\\+)?\\d+$", msg = "only positive numbers can be entered!") Integer pageIndex
            , @Param(value = "^(-|\\+)?\\d+$", msg = "only positive numbers can be entered!") Integer pageSize
            , Long[] catIds) throws SQLException {
        Page page = articleService.queryPage(pageIndex, pageSize, catIds);
        return Json.ui(page);
    }

    /**
     * 保存文章数据
     *
     * @param article 对象 0 文章对象 文章数据
     * @return
     */
    @POST(value = "/save", name = "保存文章")
    public Object save(Article article) {
        articleService.save(article);
        return Json.success("ok");
    }

    /**
     * 查询单条文章记录
     * @param id 长整型 1 文章ID 文章数据
     * @return
     */
    @GET(value = "/find", name = "查询单条文章")
    public Object find(@Param(value = "^(-|\\+)?\\d+$", remarks = "文章ID", msg = "only positive numbers can be entered!") Long id) {
        Article article = articleService.find(id);
        return Json.success(article);
    }

    @POST("/update")
    public Object update(Article article) {
        int res = articleService.update(article);
        return Json.success(res);
    }

    @POST("/delete")
    public Object delete(Long[] ids, HttpServletRequest request) {
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        //存在旧文件就删除
        int result = articleService.delete(ids, rootPath);
        return Json.success(result);
    }

    @GET("/test")
    public Object test(@Param String key, HttpServletRequest request) {
        boolean mobileDevice = DeviceKit.isMobileDevice(request);
        if(mobileDevice) {
            WebSocketTips.sendMessage(key, "推送消息到00001!");
            return "<div style='text-align:center;'>ok</div>";
        }
        return Json.fail("只能用手机访问!");
    }
}
